package com.Liux.blog.controller;

import com.Liux.blog.entity.User;
import com.Liux.blog.service.UserService;
import com.Liux.blog.util.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Controller

public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/login")
    public ModelAndView login(ModelAndView modelAndView){
        modelAndView.setViewName("login");
        return modelAndView;
    }

    @PostMapping("/login")
    public String login(ModelAndView modelAndView, HttpServletRequest request,
                              BindingResult bindingResult, HttpServletResponse response){
        if(bindingResult.hasErrors()){
            modelAndView.addObject("error",bindingResult.getFieldError().getDefaultMessage());
//            modelAndView.setViewName("login");
//            return modelAndView;
            return "login";
        }
        String name = request.getParameter("userName");
        String pwd = request.getParameter("password");
        pwd = MD5Utils.md5(pwd);
        List<User> users = userService.loginPwd(name, pwd);
        for (User u:
             users) {
            System.out.println(u);
        }
        if(users.size()>0){
            Cookie cookie = new Cookie("userId",users.get(0).getId());
            cookie.setMaxAge(60*60*24*7);//设置Coolie在客户端的持久时间 7天后过期
            response.addCookie(cookie);
            modelAndView.setViewName("index");
            modelAndView.addObject("username",name);
            return "redirect:/index";
//            return modelAndView;
        }else{
//            modelAndView.setViewName("login");
//            return modelAndView;
            return "login";
        }

    }
    @GetMapping("/regist")
    public ModelAndView regist(ModelAndView modelAndView){
        modelAndView.setViewName("regist");
        return modelAndView;
    }


}
